import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  onLoad({ point, building, room }) {
    this.setData({
      point: point,
      building: building,
      room: room,
    })
  },
  data: {
    id: '',
    point: '',
    building: '',
    room: '',
    name: '',
    gender: null,
    mobile: '',
    idcardFrontUrl: '',
    idcardBackUrl: '',
  },
  rules: {
    name: [
      { required: true, message: '姓名不能为空!' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, message: '请输入正确的姓名!' },
    ],
    gender: [{ pattern: /[01]/, message: '性别不能为空!' }],
    idcardFrontUrl: [{ pattern: /[01]/, message: '正面不能为空!' }],
    idcardBackUrl: [{ pattern: /[01]/, message: '反面不能为空!' }],
    mobile: [
      { required: true, message: '手机号不能为空!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请输入正确的手机号!' },
    ],
  },
  async chooseMedia({ mark: { type } }) {
    const { tempFiles } = await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
    })
    if (tempFiles[0].size > 1024 * 1024) {
      wx.utils.toast('图片大小不能超过1M')
      return
    }
    //  上传图片
    this.setData({ [type]: tempFiles[0].tempFilePath })
    const res = await wx.http.upload('/upload', {
      name: 'file',
      filePath: tempFiles[0].tempFilePath,
    })
    console.log(res)
  },
  async goList() {
    const val = this.validate()
    // eslint-disable-next-line no-unused-vars
    const { __webviewId__, id, ...form } = this.data
    if (val) {
      const res = await wx.http.post('/room', form)
      wx.utils.toast(res.message)
      wx.navigateBack({ delta: 4 })
    }
    // wx.reLaunch({
    //   url: '/house_pkg/pages/list/index',
    // })
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({ [type]: '' })
  },
})
